<template>
  <div class="home">
    <!-- 头部导航 -->
    <header class="header" :style="headerStyle">
      <div class="container">
        <div class="logo">
          <h1>{{ userStore.titleName}}</h1>
        </div>
        <nav class="nav">
          <router-link to="/" class="nav-item active">首页</router-link>
          <router-link to="/login" v-if="!userStore.isLoggedIn" class="nav-item">登录</router-link>
          <router-link to="/user" v-if="userStore.isLoggedIn" class="nav-item">个人中心</router-link>
          <router-link to="/admin" v-if="userStore.isAdmin" class="nav-item">管理后台</router-link>
          <el-button v-if="userStore.isLoggedIn" @click="logout" type="text">退出</el-button>
        </nav>
      </div>
    </header>

    <!-- Banner轮播区域 -->
    <div class="banner-section">
      <div class="banner-container">
        <el-carousel height="400px" indicator-position="outside" arrow="always" class="banner-carousel">
          <el-carousel-item v-for="(img, idx) in bannerImages" :key="idx">
            <img :src="img" class="banner-img" alt="banner" />
          </el-carousel-item>
        </el-carousel>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section" :style="searchSectionStyle">
      <div class="container">
        <div class="search-content">
          <div class="search-title">
            <h2>找工作</h2>
            <p>找到最适合你的工作机会</p>
          </div>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索岗位、公司或地点"
              class="search-input"
              clearable
              size="large"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button 
              type="primary" 
              @click="handleSearch" 
              class="search-btn" 
              size="large"
              :loading="loading"
              :disabled="loading"
            >
              {{ loading ? '搜索中...' : '搜索' }}
            </el-button>
          </div>
          <div class="search-tags">
            <span class="tag-label">热门搜索：</span>
            <el-tag 
              v-for="tag in hotTags" 
              :key="tag" 
              class="hot-tag"
              @click="searchKeyword = tag"
            >
              {{ tag }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 快速分类 -->
    <!--<div class="category-section">-->
      <!--<div class="container">-->
        <!--<div class="category-grid">-->
          <!--<div -->
            <!--v-for="category in categories" -->
            <!--:key="category.name"-->
            <!--class="category-item"-->
            <!--@click="handleCategoryClick(category)"-->
          <!--&gt;-->
            <!--<div class="category-icon">-->
              <!--<el-icon><component :is="category.icon" /></el-icon>-->
            <!--</div>-->
            <!--<div class="category-info">-->
              <!--<h3>{{ category.name }}</h3>-->
              <!--<p>{{ category.count }}个岗位</p>-->
            <!--</div>-->
          <!--</div>-->
        <!--</div>-->
      <!--</div>-->
    <!--</div>-->

    <!-- 岗位列表 -->
    <div class="job-list-section">
      <div class="container">
        <!-- 全局加载状态 -->
        <div v-if="loading && filteredJobs.length === 0" class="loading-container">
          <el-skeleton :rows="5" animated />
        </div>
        
        <div v-else>
          <div class="section-header">
            <div class="section-title">
              <h2>最新岗位</h2>
              <p>发现更多优质工作机会</p>
            </div>
            <div class="section-actions">
              <el-button 
                type="primary" 
                plain 
                @click="refreshJobs"
                :loading="loading"
                :disabled="loading"
              >
                <el-icon><Refresh /></el-icon>
                {{ loading ? '刷新中...' : '刷新' }}
              </el-button>
            </div>
          </div>
        
        <!-- 搜索结果统计 -->
        <div v-if="searchKeyword.trim()" class="search-result-info">
          <p>搜索"{{ searchKeyword }}"的结果：共找到 {{ total }} 个岗位</p>
        </div>

        <!-- 岗位列表 -->
        <div v-if="filteredJobs.length > 0" class="job-list">
          <div
            v-for="job in filteredJobs"
            :key="job.positionId"
            class="job-card"
            @click="goToJobDetail(job.positionId)"
          >
            <div class="job-header">
              <h3 class="job-title">{{ job.title }}</h3>
              <span class="job-salary">{{ job.salary }}</span>
            </div>
            
            <div class="job-company">
              <el-icon><OfficeBuilding /></el-icon>
              <span>{{ job.company }}</span>
            </div>
            
            <div class="job-info">
              <div class="info-item">
                <el-icon><Location /></el-icon>
                <span>{{ job.location }}</span>
              </div>
              <div class="info-item">
                <el-icon><Clock /></el-icon>
                <span>{{ job.experience }}</span>
              </div>
              <div class="info-item">
                <el-icon><School /></el-icon>
                <span>{{ job.education }}</span>
              </div>
            </div>
            
            <div class="job-description">
              {{ job.description }}
            </div>
            
            <div class="job-footer">
              <span class="publish-time">{{ job.publishTime }}</span>
              <el-button type="primary" size="small" @click.stop="shareJob(job)">
                分享
              </el-button>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else-if="!loading" class="empty-state">
          <el-empty 
            :description="searchKeyword.trim() ? `没有找到包含'${searchKeyword}'的岗位` : '暂无岗位信息'"
            :image-size="200"
          >
            <el-button type="primary" @click="refreshJobs">刷新</el-button>
          </el-empty>
        </div>

        <!-- 加载更多 -->
        <div v-if="hasMore && filteredJobs.length > 0" class="load-more">
          <el-button 
            type="primary" 
            plain 
            @click="loadMoreJobs"
            :loading="loading"
            :disabled="loading"
          >
            {{ loading ? '加载中...' : '加载更多岗位' }}
          </el-button>
        </div>

        <!-- 已加载全部 -->
        <div v-else-if="filteredJobs.length > 0 && !hasMore" class="load-more">
          <p class="no-more">已加载全部岗位</p>
        </div>
        </div>
      </div>
    </div>

    <!-- 分享对话框 -->
    <el-dialog v-model="shareDialogVisible" title="分享岗位信息" width="500px">
      <div class="share-content">
        <div class="share-info">
          <h4>{{ selectedJob?.title }}</h4>
          <p>{{ selectedJob?.company }} | {{ selectedJob?.location }} | {{ selectedJob?.salary }}</p>
        </div>
        
        <div class="share-link">
          <el-input
            :value="shareLink"
            readonly
            class="share-input"
          >
            <template #append>
              <el-button @click="copyShareLink">复制链接</el-button>
            </template>
          </el-input>
        </div>
        
        <div class="share-qr" v-if="shareQrCode">
          <img :src="shareQrCode" alt="分享二维码" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useJobsStore } from '@/stores/jobs'
import { mockJobs } from '@/mock/data'
import { ElMessage } from 'element-plus'
import { getUserList, getPositionList,getWwwinfoList, positionAdd, positionUpdate,positionUpdateStatus, positionDel } from "@/api/system"

const router = useRouter()
const userStore = useUserStore()
const jobsStore = useJobsStore()

const searchKeyword = ref('')
const shareDialogVisible = ref(false)
const selectedJob = ref(null)
const shareLink = ref('')
const shareQrCode = ref('')

// 分页相关
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)

// 过滤后的岗位列表
const filteredJobs = ref([])

// 过滤后的网站列表
const filteredIndexs = ref([])

// 热门搜索标签
const hotTags = [
  '前端开发', '后端开发', '产品经理', 'UI设计师', 
  '数据分析师', '运营专员', '销售经理', '财务专员'
]

// 快速分类
const categories = [
  { name: '技术开发', icon: 'Monitor', count: 1250 },
  { name: '产品设计', icon: 'Brush', count: 680 },
  { name: '运营市场', icon: 'Promotion', count: 920 },
  { name: '销售商务', icon: 'Service', count: 1100 },
  { name: '人事行政', icon: 'User', count: 450 },
  { name: '财务法务', icon: 'Document', count: 380 }
]


// 获取岗位列表
const getJobListAll = async (isLoadMore = false) => {
  try {
    loading.value = true
    
    // 构建查询参数
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value
    }
    
    // 如果有搜索关键词，添加到参数中
    if (searchKeyword.value.trim()) {
      params.keyword = searchKeyword.value.trim()
    }
    
    const response = await getPositionList(params)
    
    if (response && response.rows) {
      if (isLoadMore) {
        // 加载更多时，追加数据
        filteredJobs.value = [...filteredJobs.value, ...response.rows]
      } else {
        // 首次加载或搜索时，替换数据
        filteredJobs.value = response.rows
      }
      
      total.value = response.total || 0
      
      // 判断是否还有更多数据
      hasMore.value = filteredJobs.value.length < total.value
    }
  } catch (error) {
    console.error('获取岗位列表失败:', error)
    ElMessage.error('获取岗位列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索功能
const handleSearch = async () => {
  // 重置分页
  pageNum.value = 1
  hasMore.value = true
  
  // 执行搜索
  await getJobListAll(false)
  
  if (searchKeyword.value.trim()) {
    ElMessage.success(`搜索"${searchKeyword.value}"完成，找到${filteredJobs.value.length}个岗位`)
  }
}

// 监听搜索关键词变化，实现实时搜索（可选）
watch(searchKeyword, (newVal, oldVal) => {
  // 如果用户清空了搜索框，自动刷新列表
  if (oldVal && !newVal) {
    handleSearch()
  }
}, { deep: true })

// Banner图片数组
const bannerImages = ref([
  new URL('@/assets/index/1.png', import.meta.url).href,
  new URL('@/assets/index/2.png', import.meta.url).href,
  new URL('@/assets/index/9.png', import.meta.url).href,
  new URL('@/assets/index/10.png', import.meta.url).href
])

// 背景图片配置
const headerBgImage = ref('')
const searchSectionBgImage = ref('')

// 头部样式计算属性
const headerStyle = computed(() => {
  if (headerBgImage.value) {
    return {
      backgroundImage: `url(${headerBgImage.value})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat'
    }
  }
  return {}
})

// 搜索区域样式计算属性
const searchSectionStyle = computed(() => {
  if (searchSectionBgImage.value) {
    return {
      backgroundImage: `url(${searchSectionBgImage.value})`,
      backgroundSize: 'cover',
      backgroundPosition: 'center',
      backgroundRepeat: 'no-repeat'
    }
  }
  return {}
})

// 获取网站列表
const getIndexListAll = async (isLoadMore = false) => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100
    }
    localStorage.setItem('IndexObjName', "")

    const response = await getWwwinfoList(params)

    if (response && response.rows) {
      // 首次加载或搜索时，替换数据
      filteredIndexs.value = response.rows.filter(r=>r.status == 'active')
      if(filteredIndexs.value.length == 1){
        const config = filteredIndexs.value[0]
        localStorage.setItem('IndexObjName', config.wwwName)

        // 设置轮播图
        if (config.bannerUrl) {
          const newArr = JSON.parse(config.bannerUrl)
          if(newArr.length>0){
            bannerImages.value = newArr.map(r=>r.url)
          }
        }
        
        // 设置头部背景图片
        if (config.firstUrl) {
          const newArrTwo = JSON.parse(config.firstUrl)
          if(newArrTwo.length>0){
            headerBgImage.value = newArrTwo.map(r=>r.url)[0]
          }
        }
        
        // 设置搜索区域背景图片
        if (config.searchUrl) {
          const newArrThree = JSON.parse(config.searchUrl)
          if(newArrThree.length>0){
            searchSectionBgImage.value = newArrThree.map(r=>r.url)[0]
          }
        }
      }

    }
  } catch (error) {
    console.error('获取网站列表失败:', error)
    ElMessage.error('获取网站列表失败')
  } finally {
    loading.value = false
  }
}

// 初始化数据
onMounted(() => {
  jobsStore.setJobs(mockJobs)
  getJobListAll()
  getIndexListAll()
})


// 分类点击
const handleCategoryClick = (category) => {
  searchKeyword.value = category.name
  handleSearch()
}

// 刷新岗位
const refreshJobs = async () => {
  // 重置分页
  pageNum.value = 1
  hasMore.value = true
  
  await getJobListAll()
  ElMessage.success('岗位列表已刷新')
}

// 加载更多
const loadMoreJobs = async () => {
  if (loading.value || !hasMore.value) return
  
  pageNum.value += 1
  await getJobListAll(true)
  
  if (!hasMore.value) {
    ElMessage.info('已加载全部岗位')
  }
}

// 跳转到岗位详情
const goToJobDetail = (jobId) => {
  router.push(`/job/${jobId}`)
}

// 分享岗位
const shareJob = (job) => {
  selectedJob.value = job
  shareLink.value = `${window.location.origin}/job/${job.positionId}`
  const shareUserId =  localStorage.getItem('user') && typeof localStorage.getItem('user') != 'string'? JSON.parse(localStorage.getItem('user'))?.userId : null
  if(shareUserId){
    shareLink.value = `${window.location.origin}/job/${job.positionId}?shareUserId=${shareUserId}`
  }

  shareDialogVisible.value = true
}

// 复制分享链接
const copyShareLink = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('链接已复制到剪贴板')
  } catch (err) {
    ElMessage.error('复制失败')
  }
}

// 退出登录
const logout = () => {
  userStore.logout()
  router.push('/')
  ElMessage.success('已退出登录')
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  background-color: #f8f9fa;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 头部样式 */
.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 15px 0;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  position: relative;
}

/* 头部背景遮罩，确保文字清晰可见 */
.header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  z-index: -1;
}

.header .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 1;
}

.logo h1 {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.nav {
  display: flex;
  align-items: center;
  gap: 20px;
}

.nav-item {
  color: white;
  text-decoration: none;
  padding: 8px 16px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.nav-item:hover,
.nav-item.active {
  background-color: rgba(255,255,255,0.2);
}

/* Banner区域 */
.banner-section {
  background: #fff;
  padding: 20px 0;
  border-bottom: 1px solid #eee;
}

.banner-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.banner-carousel {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}

.banner-img {
  width: 100%;
  height: 400px;
  object-fit: cover;
}

/* 搜索区域 */
.search-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 0;
  color: white;
  position: relative;
}

/* 搜索区域背景遮罩，确保文字清晰可见 */
.search-section::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 0;
}

.search-content {
  text-align: center;
  max-width: 800px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

.search-title h2 {
  font-size: 32px;
  margin: 0 0 10px 0;
  font-weight: bold;
}

.search-title p {
  font-size: 16px;
  margin: 0 0 30px 0;
  opacity: 0.9;
}

.search-box {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  background: rgba(255,255,255,0.1);
  padding: 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.search-input {
  flex: 1;
}

.search-input :deep(.el-input__wrapper) {
  background: white;
  border: none;
  border-radius: 8px;
}

.search-btn {
  padding: 0 40px;
  border-radius: 8px;
  font-weight: bold;
}

.search-tags {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-label {
  font-size: 14px;
  opacity: 0.9;
}

.hot-tag {
  cursor: pointer;
  transition: all 0.3s;
  background: rgba(255,255,255,0.2);
  border: 1px solid rgba(255,255,255,0.3);
  color: white;
}

.hot-tag:hover {
  background: rgba(255,255,255,0.3);
  transform: translateY(-1px);
}

/* 分类区域 */
.category-section {
  background: white;
  padding: 40px 0;
  border-bottom: 1px solid #eee;
}

.category-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 20px;
  border-radius: 12px;
  background: #f8f9fa;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #eee;
}

.category-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.category-icon {
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.category-info h3 {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.category-info p {
  margin: 0;
  font-size: 14px;
  color: #666;
}

/* 岗位列表 */
.job-list-section {
  padding: 40px 0;
  background: white;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

.section-title h2 {
  font-size: 28px;
  color: #333;
  margin: 0 0 5px 0;
}

.section-title p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.job-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
  gap: 20px;
  margin-bottom: 40px;
}

.job-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  transition: all 0.3s;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.job-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
  border-color: #667eea;
}

.job-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.job-title {
  font-size: 18px;
  color: #333;
  margin: 0;
  flex: 1;
  font-weight: 600;
}

.job-salary {
  color: #e74c3c;
  font-weight: bold;
  font-size: 16px;
}

.job-company {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  margin-bottom: 15px;
  font-size: 14px;
}

.job-info {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
  font-size: 13px;
}

.job-description {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  font-size: 14px;
}

.job-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.publish-time {
  color: #999;
  font-size: 12px;
}

.load-more {
  text-align: center;
  margin-top: 40px;
}

.no-more {
  color: #999;
  font-size: 14px;
  margin: 0;
}

.search-result-info {
  background: #f8f9fa;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #667eea;
}

.search-result-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.loading-container {
  padding: 40px 0;
}

/* 分享对话框 */
.share-content {
  text-align: center;
}

.share-info {
  margin-bottom: 20px;
}

.share-info h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.share-info p {
  margin: 0;
  color: #666;
}

.share-link {
  margin-bottom: 20px;
}

.share-input {
  width: 100%;
}

.share-qr {
  margin-top: 20px;
}

.share-qr img {
  max-width: 200px;
  border: 1px solid #eee;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 0 15px;
  }
  
  .header .container {
    flex-direction: column;
    gap: 15px;
  }
  
  .nav {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .banner-img {
    height: 200px;
  }
  
  .search-title h2 {
    font-size: 24px;
  }
  
  .search-box {
    flex-direction: column;
    padding: 15px;
  }
  
  .search-tags {
    justify-content: flex-start;
  }
  
  .category-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .category-item {
    padding: 15px;
  }
  
  .category-icon {
    width: 40px;
    height: 40px;
    font-size: 20px;
  }
  
  .job-list {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .job-card {
    padding: 20px;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .job-info {
    gap: 15px;
  }
}

@media (max-width: 480px) {
  .category-grid {
    grid-template-columns: 1fr;
  }
  
  .search-tags {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .job-info {
    flex-direction: column;
    gap: 10px;
  }
}
</style> 